<?php

namespace App\Http\Controllers;

use App\Models\Sync;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\ContractTransaction;
use Illuminate\Support\Facades\Input;

class ContractController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $transactions = DB::table('contract_transactions');

        if ($request->from) {
            $transactions = $transactions->where(function($query) use ($request) {
                $query->where('from', $request->from)
                        ->orWhere('to', $request->from);
            });
        }

        if ($request->start_date) {
            $transactions = $transactions->where('timeStamp', '>=', strtotime($request->start_date));
        }

        if ($request->end_date) {
            $Transactions = $transactions->where('timeStamp', '<=', strtotime($request->end_date));
        }

        if ($request->type == 1) {
            $transactions = $transactions->where('input', '0x');
        } elseif ($request->type == 2) {
            $transactions = $transactions->where('input', '!=', '0x');
        }

        $transactions = $transactions->orderBy('timeStamp', 'desc')->paginate(15);

        $query_string = Input::only(['from', 'type']);

        $transactions->appends($query_string);

        $last_sync = Sync::where('type', 'contract')->orderBy('created_at', 'desc')->first();
        
        return view('contract.index', ['transactions' => $transactions, 'last_sync' => $last_sync]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $transaction = ContractTransaction::find($id);
        return view('contract.show', ['transaction' => $transaction]);
    }

    
}
